﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace APPWG4806.Helper
{
    public static class DataTableExtensions
    {
        /// <summary>
        /// 把DataTable转换为对应的EntryList
        /// </summary>
        /// <typeparam name="T">对应的Entry</typeparam>
        /// <param name="dataTable">DataTable数据</param>
        /// <returns></returns>
        public static List<T> ToList<T>(this DataTable dataTable) where T : new()
        {
            if (dataTable == null)
            {
                throw new ArgumentNullException(nameof(dataTable), "DataTable cannot be null.");
            }

            List<T> list = new List<T>();
            PropertyInfo[] properties = typeof(T).GetProperties();

            foreach (DataRow row in dataTable.Rows)
            {
                T item = new T();
                foreach (PropertyInfo property in properties)
                {
                    if (dataTable.Columns.Contains(property.Name))
                    {
                        object value = row[property.Name];
                        if (value == DBNull.Value)
                        {
                            property.SetValue(item, null, null);
                        }
                        else
                        {
                            try
                            {
                                property.SetValue(item, Convert.ChangeType(value, property.PropertyType), null);
                            }
                            catch (Exception ex)
                            {
                                throw new InvalidOperationException($"Error converting value '{value}' to property '{property.Name}' of type '{property.PropertyType}'.", ex);
                            }
                        }
                    }
                    else
                    {
                        throw new InvalidOperationException($"Column '{property.Name}' not found in DataTable.");
                    }
                }
                list.Add(item);
            }
            return list;
        }
    }
}
